package com.xuchang.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuchang.domain.User;
import com.xuchang.domain.UserAuthAuditRecord;
import com.xuchang.domain.UserAuthInfo;
import com.xuchang.dto.UserDto;
import com.xuchang.mapper.UserMapper;
import com.xuchang.mappers.UserDtoMapper;
import com.xuchang.model.*;
import com.xuchang.service.UserAuthAuditRecordService;
import com.xuchang.service.UserAuthInfoService;
import com.xuchang.service.UserService;
import com.xuchang.vo.UserAuthInfoVo;
import jdk.nashorn.internal.ir.CallNode;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserAuthInfoService userAuthInfoService;

    @Autowired
    private UserAuthAuditRecordService userAuthAuditRecordService;

    @Override
    public Page<User> findByPage(Page<User> page, String mobile, Long userId, String userName, String realName, Integer status, Integer reviewStatus) {
        return page(page,
                new LambdaQueryWrapper<User>()
                        .like(!StringUtils.isEmpty(mobile), User::getMobile, mobile)
                        .like(!StringUtils.isEmpty(userName), User::getUsername, userName)
                        .like(!StringUtils.isEmpty(realName), User::getRealName, realName)
                        .eq(userId != null, User::getId, userId)
                        .eq(status != null, User::getStatus, status)
                        .eq(reviewStatus != null, User::getReviewsStatus, reviewStatus)
        );
    }

    @Override
    public Page<User> findDirectInvitePage(Page<User> page, Long userId) {
        return page(page, new LambdaQueryWrapper<User>().eq(User::getDirectInviteid, userId));
    }

    @Override
    @Transactional
    public void updateUserAuthStatus(Long id, Byte authStatus, Long authCode, String remark) {
        User user = super.getById(id);
        if(user != null){
            user.setReviewsStatus(Integer.valueOf(authStatus));
            updateById(user);
            UserAuthAuditRecord userAuthAuditRecord = new UserAuthAuditRecord();
            userAuthAuditRecord.setStatus(authStatus);
            userAuthAuditRecord.setUserId(id);
            userAuthAuditRecord.setRemark(remark);

            String userStr = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
            userAuthAuditRecord.setAuditUserId(Long.valueOf(userStr)); // 审核人的ID
            userAuthAuditRecord.setAuditUserName("---------------------------");// 审核人的名称 --> 远程调用admin-service ,没有事务
            userAuthAuditRecordService.save(userAuthAuditRecord);
        }
    }

    @Override
    public boolean identifyVerify(Long id, UserAuthForm userAuthForm) {
        return false;
    }

    @Override
    public void authUser(Long id, List<String> imgs) {

    }

    @Override
    public boolean updatePhone(Long userId, UpdatePhoneParam updatePhoneParam) {
        return false;
    }

    @Override
    public boolean checkNewPhone(String mobile, String countryCode) {
        return false;
    }

    @Override
    public boolean updateUserLoginPwd(Long userId, UpdateLoginParam updateLoginParam) {
        return false;
    }

    @Override
    public boolean updateUserPayPwd(Long userId, UpdateLoginParam updateLoginParam) {
        return false;
    }

    @Override
    public boolean unsetPayPassword(Long userId, UnsetPayPasswordParam unsetPayPasswordParam) {
        return false;
    }

    @Override
    public List<User> getUserInvites(Long userId) {
        return Collections.emptyList();
    }

    @Override
    public boolean register(RegisterParam registerParam) {
        return false;
    }

    @Override
    public boolean unsetLoginPwd(UnSetPasswordParam unSetPasswordParam) {
        return false;
    }

    @Override
    public UserAuthInfoVo getUseAuthInfo(Long id) {
        UserAuthInfoVo userAuthInfoVo = new UserAuthInfoVo();
        User user = super.getById(id);
        if (user != null) {
            userAuthInfoVo.setUser(user);
            // 用户的审核记录
            Integer reviewsStatus = user.getReviewsStatus();
            List<UserAuthAuditRecord> userAuthAuditRecordList = null;
            List<UserAuthInfo> userAuthInfoList = null;
            if (reviewsStatus == null || reviewsStatus == 0) {
                userAuthAuditRecordList = Collections.emptyList(); // 用户没有审核记录
                userAuthInfoList = userAuthInfoService.getUserAuthInfoByUserId(id);
            } else {
                userAuthAuditRecordList = userAuthAuditRecordService.getUserAuthAuditRecordList(id);
                UserAuthAuditRecord userAuthAuditRecord = userAuthAuditRecordList.get(0);
                Long authCode = userAuthAuditRecord.getAuthCode();
                userAuthInfoList = userAuthInfoService.getUserAuthInfoByCode(authCode);
            }

            userAuthInfoVo.setUserAuthInfoList(userAuthInfoList);
            userAuthInfoVo.setAuthAuditRecordList(userAuthAuditRecordList);

            return userAuthInfoVo;
        }
        return null;
    }

    /**
     * 通过用户的信息查询用户
     *
     * @param ids      用户的批量查询,用在我们给别人远程调用时批量获取用户的数据
     * @param userName 使用用户名查询一系列用户的记录
     * @param mobile   使用用户手机查询一系列用户的记录
     * @return
     */
    @Override
    public Map<Long, UserDto> getBasicUsers(List<Long> ids, String userName, String mobile) {
        if (CollectionUtils.isEmpty(ids) && StringUtils.isEmpty(userName) && StringUtils.isEmpty(mobile)) {
            return Collections.emptyMap();
        }
        List<User> list = list(new LambdaQueryWrapper<User>()
                .in(!CollectionUtils.isEmpty(ids), User::getId, ids)
                .like(!StringUtils.isEmpty(userName), User::getUsername, userName)
                .like(!StringUtils.isEmpty(mobile), User::getMobile, mobile));
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyMap();
        }
        // 将user->userDto
        List<UserDto> userDtos = UserDtoMapper.INSTANCE.convert2Dto(list);
        Map<Long, UserDto> userDtoIdMappings = userDtos.stream().collect(Collectors.toMap(UserDto::getId, userDto -> userDto));
        return userDtoIdMappings;
    }
}